package cn.example.vip.mall.order.service.impl;

import cn.example.vip.mall.cart.entity.Cart;
import cn.example.vip.mall.cart.feign.CartFeign;
import cn.example.vip.mall.goods.feign.SkuFeign;
import cn.example.vip.mall.order.entity.Order;
import cn.example.vip.mall.order.entity.OrderSku;
import cn.example.vip.mall.order.mapper.OrderMapper;
import cn.example.vip.mall.order.mapper.OrderSkuMapper;
import cn.example.vip.mall.order.service.OrderService;
import cn.example.vip.mall.util.RespResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private OrderSkuMapper orderSkuMapper;
	@Autowired
	private SkuFeign skuFeign;
	@Autowired
	private CartFeign cartFeign;
//	@Autowired
//	private AddressFeign addressFeign;
	
	/**
	 * 添加订单
	 * @param order
	 * @return
	 */
	@GlobalTransactional(rollbackFor = Exception.class)
	@Transactional
	@Override
	public Boolean addOrder(Order order) {
		// 设置订单信息
//		order.setId(IdWorker.getIdStr());
//		order.setCreateTime(Date.from(Instant.now()));
//		order.setUpdateTime(Date.from(Instant.now()));
		
		// 1.获取购物车
		RespResult<List<Cart>> respResult = cartFeign.queryCarts(order.getCartIds());
		List<Cart> carts = respResult.getData();
		if(carts==null || carts.size() <= 0){
			return false;
		}
		
		// 2.设置订单明细
		Integer totalSkuCount = 0;	// 商品计数
		Integer totalOrderMoney = 0;	// 订单总金额
		for(Cart cart : carts){
			OrderSku orderSku = JSON.parseObject(JSON.toJSONString(cart), OrderSku.class);
			orderSku.setId(IdWorker.getIdStr());	// 设置订单明细 id
			orderSku.setOrderId(order.getId());		// 设置订单 id
			orderSku.setMoney(cart.getNum() * orderSku.getPrice());
			orderSkuMapper.insert(orderSku);
			
			// 统计商品数与总金额
			totalSkuCount += cart.getNum();
			totalOrderMoney += cart.getNum() * cart.getPrice();
		}
		
		// 3.添加订单
		order.setTotalNum(totalSkuCount);
		order.setMoneys(totalOrderMoney);
		// 数据填充
		order.setPayTime(Date.from(Instant.now()));	// 暂存一个时间(订单支付状态由 payStatus 决定)
		order.setConsignTime(Date.from(Instant.now().plusSeconds(86400 * 3)));	// 未知,填写估计值(三天内发货)
		order.setEndTime(Date.from(Instant.now().plusSeconds(86400 * 14)));				// 未知时间,预计14天
		System.err.println(order);
		orderMapper.insert(order);
//		orderMapper.addOrderByObj(order);
		
		// 4.减库存
		skuFeign.dcount(carts);
 	
		// 5.删除购物车记录
		cartFeign.delCarts(order.getCartIds());
		
		return true;
	}
}
